package gamehandler

import (
	"context"
	"runtime"
	"wanyu/server/api/gameapi/session"
	errors "wanyu/server/engine/wperror"
	"wanyu/server/protogo/gamebase"
	"wanyu/server/protogo/gateway"

	//"wanyu/webbackend/common/log"

	log "wanyu/server/engine/wplog"
	rpc "wanyu/server/protogo/gameapi"

	"github.com/golang/protobuf/ptypes"
)

type StreamSrv struct{}

func (ge *StreamSrv) GameEvent(ctx context.Context, steam rpc.GameEvent_GameEventStream) error {
	for {
		req, ec := steam.Recv()
		if nil != ec {
			log.Errorf("error transaction with gateway, ec = %v, prepare remove players", ec)
			session.StreamExit(steam)
			return ec
		}

		ge.procGameEvent(steam, req)
	}
	return nil
}

func (ge *StreamSrv) procGameEvent(steam rpc.GameEvent_GameEventStream, event *gamebase.GameEvent) {
	defer func() {
		if r := recover(); r != nil {
			err := r.(error)
			log.Errorf("procGameEvent error: %v", err)
			buf := make([]byte, 2048)
			length := runtime.Stack(buf, false)
			log.Error(string(buf[:length]))
		}
	}()

	//fmt.Printf("****************************玩家请求:%v**************************",event.Event.Type)

	switch gateway.EventType(event.Event.Type) {
	//玩家进入房间、玩家掉线重进房间、暂时离开的玩家重进房间
	case gateway.EventType_enterRoom:
		var req gamebase.EnterRoom
		log.Debugf("******************** get enterRoom msg from client")
		ec := ptypes.UnmarshalAny(event.Event.Data, &req)
		errors.Check(nil == ec, errors.ErrorUnmarPb, "un marshal pb is failed when enter room")
		session.AddPlayer(event.PlayerID, steam, req.ConnetId)

		if !roomMgr.EnterRoom(event.PlayerID, req.PlayerIp, req.KindID, req.PlayerType, req.TargetPlayerId, "") {
			session.SendMsg(gamebase.GameEvent{
				PlayerID: event.PlayerID,
				Event: &gateway.GameEvent{
					Type:   int32(gateway.EventType_kickPlayer),
					Failed: true,
				},
			})
			session.RmPlayerToRoom(event.PlayerID, req.KindID)
			session.RemovePlayer(event.PlayerID)
		}
	//玩家离开房间
	case gateway.EventType_leavelRoom:
		session.RemovePlayer(event.PlayerID)
		roomMgr.LeaveRoom("gw", event.PlayerID, 0) //0为正常移除，1为踢玩家，3为挤玩家下线
	//玩家掉线
	case gateway.EventType_playerDisConn:
		session.RemovePlayer(event.PlayerID)
		roomMgr.PlayerDisConn(event.PlayerID)
		//主动换房
	case gateway.EventType_matchNewRoom:
		roomMgr.MatchNewRoom(event.PlayerID)
	//	玩家点击离开按钮
	//case gateway.EventType_exitRoom :

		//srvStrs := strings.Split(roomMgr.GetMicroSrvName(), ".")
		//switch  srvStrs[len(srvStrs)-1] {
		//case "ddz", "fkddz":
		//	if roomMgr.GetRoomPlayerCnt(event.PlayerID) >= 3 {   // cannot leave
		//		session.SendMsg(gamebase.GameEvent{
		//			PlayerID: event.PlayerID,
		//			Event: &gateway.GameEvent{
		//				Type:   int32(gateway.EventType_exitRoom),
		//				Failed: true,
		//				JsonData: "{ \"exitroom\": false }",
		//			},
		//		})
		//		return
		//	}
		//case "xzdd":
		//	if roomMgr.GetRoomPlayerCnt(event.PlayerID) >= 4 {  // cannot leave
		//		session.SendMsg(gamebase.GameEvent{
		//			PlayerID: event.PlayerID,
		//			Event: &gateway.GameEvent{
		//				Type:   int32(gateway.EventType_exitRoom),
		//				Failed: true,
		//				JsonData: "{ \"exitroom\": false }",
		//			},
		//		})
		//		return
		//	}
		//}

		//roomMgr.ExitRoom("gw", event.PlayerID, 0)

	default: //游戏事件
		log.Debug("****************** in default case, event: '%v'", event)
		roomMgr.PostGameEvent(*event)

	}
}
